package com.rabbit.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.rabbit.service.ValidateCodeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;

/**
 * <h1>验证码</h1>
 *
 * @author zjw
 * @date 2022/1/13 9:02
 */
@RestController
@RequestMapping("/validate")
public class VerifyCodeController {

    @Resource
    private ValidateCodeService validateCodeService;

    /**
     * 生成验证码
     */
    @GetMapping("/code/{deviceId}")
    public void generateVerifyCode(@PathVariable String deviceId, HttpServletResponse response) throws IOException {
        response.setContentType("image/gif");
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(160, 60, 4, 5);
        captcha.setFont(new Font("Arial,Courier", Font.BOLD, 38));
        captcha.write(response.getOutputStream());
        // 保存图形验证码到Redis
        validateCodeService.saveImageCode(deviceId, captcha.getCode().toLowerCase());
    }

}
